package com.zzyy.study.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyy.study.entities.Pay;
import com.zzyy.study.service.PayService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @auther zzyy
 * @create 2024-08-24 9:43
 */
@RestController
@Slf4j
public class PayController
{
    @Resource
    private PayService payService;

    @PostMapping(value = "/pay/add")
    public boolean addPay(@RequestBody Pay pay)
    {
        return payService.save(pay);
    }

    @GetMapping(value = "/pay/list")
    public List<Pay> list()
    {
        return payService.list();
    }


    //=========================================================
    //=========================================================
    //=========================================================
    @PostMapping(value = "/pay/myinsert")
    public int myInsert(@RequestBody Pay pay)
    {
        return payService.myInsert(pay);
    }

    @GetMapping(value = "/pay/retry")
    public void retry()
    {
        sendRetry();
    }

    /**
     * 每5秒执行一次
     */
    @Scheduled(fixedDelay = 5 * 1000)
    public void sendRetry()
    {
        AtomicInteger atomicInteger = new AtomicInteger();

        while (atomicInteger.get() <= 4)
        {
            /**
             * 查询出需要重试的消息，重新投递
             * select * from t_pay where id = 11;
             */
            LambdaQueryWrapper<Pay> lambdaQueryWrapper = new LambdaQueryWrapper();
            lambdaQueryWrapper.eq(Pay::getId,11);

            System.out.println(payService.list(lambdaQueryWrapper));
            //暂停2秒钟线程
            try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }

            System.out.println(atomicInteger.getAndIncrement() +" \t "+Thread.currentThread().getName());
        }
    }
}
